<script setup>
import myCanvas from '@/utils/myCanvas'
import { imgUploadVerify } from '@/utils/auth'
import { ref } from 'vue'
import { onReady } from '@dcloudio/uni-app'

const queryParams = ref({
    imageFileUrl: '', // 图片地址
})

let imgCanvas, rectCanvas
// 父盒子宽高
const contentDom = ref({})
// 图片尺寸
const imgRect = ref({})
// 矩形信息
const rect = ref({
    x: 50,
    y: 50,
    width: 100,
    height: 100,
    dragging: false,
    resizingCorner: null,
})

// 鼠标位置
const mousePos = ref({ x: 0, y: 0 })

function drawImageFn() {
    // 画布绘制图片
    imgCanvas.drawImage(queryParams.value.imageFileUrl, 0, 0, imgRect.value.width, imgRect.value.height)
}

// 绘制矩形
function drawRect() {
    rectCanvas.clearRect(0, 0, contentDom.value.width, contentDom.value.height)
    rectCanvas.drawDraggableBorderedRect(rect.value.x, rect.value.y, rect.value.width, rect.value.height)
}

// 相册选择
async function uploadImgFn() {
    const res = await imgUploadVerify()
    queryParams.value.imageFileUrl = res
    calculatePicAspectRatio(queryParams.value.imageFileUrl).then(() => {
        drawImageFn()
    })
}

// 计算图片宽高比及外部边框盒子的宽高
async function calculatePicAspectRatio(path) {
    const { width, height } = await uni.getImageInfo({ src: path })

    const widthRatio = contentDom.value.width / width;
    const heightRatio = contentDom.value.height / height;
    const scaleRatio = Math.min(widthRatio, heightRatio);

    // 计算缩放后的图片宽度和高度
    const scaledWidth = width * scaleRatio;
    const scaledHeight = height * scaleRatio;

    // 绘制尺寸
    imgRect.value = {
        width: scaledWidth,
        height: scaledHeight
    }
}

// 处理鼠标按下事件
function onMouseDown(e) {
    const touch = e.touches[0]
    const offsetX = touch.clientX - contentDom.value.left || 0
    const offsetY = touch.clientY - contentDom.value.top || 0
    mousePos.value = { x: offsetX, y: offsetY }

    // 检查是否点击在矩形的四个角
    const corners = [
        { x: rect.value.x, y: rect.value.y }, // 左上角
        { x: rect.value.x + rect.value.width, y: rect.value.y }, // 右上角
        { x: rect.value.x, y: rect.value.y + rect.value.height }, // 左下角
        { x: rect.value.x + rect.value.width, y: rect.value.y + rect.value.height }, // 右下角
    ]

    for (let i = 0; i < corners.length; i++) {
        const corner = corners[i]
        // 判断鼠标是否点击在角点附近
        if (Math.abs(offsetX - corner.x) < 10 && Math.abs(offsetY - corner.y) < 10) {
            rect.value.resizingCorner = i // 设置当前调整的角点索引
            return
        }
    }

    // 检查是否点击在矩形内部
    if (
        offsetX > rect.value.x &&
        offsetX < rect.value.x + rect.value.width &&
        offsetY > rect.value.y &&
        offsetY < rect.value.y + rect.value.height
    ) {
        rect.value.dragging = true // 设置拖动状态
    }
}

// 处理鼠标移动事件
function onMouseMove(e) {
    const touch = e.touches[0]
    const offsetX = touch.clientX - contentDom.value.left || 0
    const offsetY = touch.clientY - contentDom.value.top || 0
    const dx = offsetX - mousePos.value.x
    const dy = offsetY - mousePos.value.y
    mousePos.value = { x: offsetX, y: offsetY }

    const minWidth = 100
    const minHeight = 30

    if (rect.value.resizingCorner !== null) {
        // 调整矩形大小
        switch (rect.value.resizingCorner) {
            case 0: // top-left
                rect.value.x = Math.max(0, Math.min(rect.value.x + dx, rect.value.x + rect.value.width - minWidth))
                rect.value.y = Math.max(0, Math.min(rect.value.y + dy, rect.value.y + rect.value.height - minHeight))
                rect.value.width = Math.max(rect.value.width - dx, minWidth)
                rect.value.height = Math.max(rect.value.height - dy, minHeight)
                break
            case 1: // top-right
                rect.value.y = Math.max(0, Math.min(rect.value.y + dy, rect.value.y + rect.value.height - minHeight))
                rect.value.width = Math.min(Math.max(rect.value.width + dx, minWidth), contentDom.value.width - rect.value.x)
                rect.value.height = Math.max(rect.value.height - dy, minHeight)
                break
            case 2: // bottom-left
                rect.value.x = Math.max(0, Math.min(rect.value.x + dx, rect.value.x + rect.value.width - minWidth))
                rect.value.width = Math.max(rect.value.width - dx, minWidth)
                rect.value.height = Math.min(Math.max(rect.value.height + dy, minHeight), contentDom.value.height - rect.value.y)
                break
            case 3: // bottom-right
                rect.value.width = Math.min(Math.max(rect.value.width + dx, minWidth), contentDom.value.width - rect.value.x)
                rect.value.height = Math.min(Math.max(rect.value.height + dy, minHeight), contentDom.value.height - rect.value.y)
                break
        }

        // 边界判断
        rect.value.x = Math.max(0, Math.min(rect.value.x, contentDom.value.width - rect.value.width))
        rect.value.y = Math.max(0, Math.min(rect.value.y, contentDom.value.height - rect.value.height))
    } else if (rect.value.dragging) {
        // 拖动矩形
        rect.value.x = Math.max(0, Math.min(rect.value.x + dx, contentDom.value.width - rect.value.width))
        rect.value.y = Math.max(0, Math.min(rect.value.y + dy, contentDom.value.height - rect.value.height))
    }

    drawRect()
}


// 处理鼠标松开事件
function onMouseUp() {
    rect.value.dragging = false
    rect.value.resizingCorner = null
}

onReady(() => {
    uni.createSelectorQuery().select('.canvas_box').boundingClientRect((res) => {
        contentDom.value = res
        imgCanvas = new myCanvas('imgCanvas')
        rectCanvas = new myCanvas('rectCanvas')

        // 绘制初始矩形
        setTimeout(() => {
            drawRect()
        }, 300)
    }).exec()
})
</script>

<template>
    <div class='gtTest' @touchmove.stop>
        <NavBar>测试</NavBar>
        <div class="container">
            <div class="canvas_box">
                <canvas type="2d" id="imgCanvas" class="imgCanvas"></canvas>
                <canvas type="2d" id="rectCanvas" class="rectCanvas" @touchstart="onMouseDown" @touchmove.stop="onMouseMove"
                    @touchend="onMouseUp"></canvas>

                <!-- <div v-if="!queryParams.imageFileUrl" class="uploadImgBtn" @click="uploadImgFn">
                    <i class="iconfont ai-icon-xiangcexuanze"></i>
                    相册选择
                </div> -->
            </div>
        </div>
    </div>
</template>

<style lang='scss' scoped>
.gtTest {
    height: 100vh;
    display: flex;
    flex-direction: column;

    .container {
        flex: 1;

        .canvas_box {
            position: relative;
            width: 100%;
            height: 100%;

            .imgCanvas,
            .rectCanvas {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;

                &.imgCanvas {
                    z-index: 1;
                }

                &.rectCanvas {
                    z-index: 2;
                }
            }

            .uploadImgBtn {
                position: absolute;
                top: 50%;
                left: 50%;
                z-index: 3;
                transform: translate(-50%, -50%);
                width: 228rpx;
                height: 84rpx;
                border-radius: 45rpx;
                background-color: transparent;
                border: 3rpx solid var(--a-main-color);
                color: var(--a-one-text-color);
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 10rpx;
            }
        }
    }
}
</style>